#include <stdio.h>
#include "status.h"
#include "cpu.h"

long double
get_cpu(Arg * arg)
{
    long * jiffies = get_jiffies(NULL);
    long total_over_period = (long) jiffies[0] -
                            (long) arg->last_jiffies[0],
         work_over_period  = (long) jiffies[1] -
                            (long) arg->last_jiffies[1];
    return ((long double) work_over_period /
            total_over_period) * 100;
}

long *
get_jiffies(Arg * arg)
{
    static long jiffies[2];
    FILE * file;
    char name[64];
    long user    = 0,
         nice    = 0,
         system  = 0,
         idle    = 0,
         iowait  = 0,
         irq     = 0,
         softirq = 0;

    if (!(file = fopen("/proc/stat", "r"))) {
        printf("can't open /proc/stat\n");
        return jiffies;
    }

    fscanf(file, "%s  %ld %ld %ld %ld %ld %ld %ld",
                 name,
                 &user,
                 &nice,
                 &system,
                 &idle,
                 &iowait,
                 &irq,
                 &softirq);
    fclose(file);

    jiffies[0] = user + nice + system + idle + iowait + irq + softirq;
    jiffies[1] = user + nice + system;

    return jiffies;
}
